package respDownload;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
/*
* 下载文件的附件
*        Content-Type:文件的MIME类型
*        Content-Disposition:attachment;filename=文件的名称
* */
@WebServlet(value = "/respDownload/demo01")
public class respDownload extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName = request.getParameter("fileName");
        String newFileName = URLEncoder.encode(fileName, "UTF-8");
        String mimeType = this.getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment;filename=" + newFileName);
        BufferedInputStream bis = new BufferedInputStream(this.getServletContext().getResourceAsStream("/download/" + fileName));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        int b ;
        while ((b = bis.read())!=-1) {
            bos.write(b);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
